package com.ruoyi.project.in.stockin.service;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.project.bas.basJobId.domain.BasJobId;
import com.ruoyi.project.bas.basJobId.mapper.BasJobIdMapper;
import com.ruoyi.project.in.stockin.domain.InStockVo;
import com.ruoyi.project.in.stockin.domain.Stockin;
import com.ruoyi.project.in.stockin.mapper.StockinMapper;
import com.ruoyi.project.in.stockindetail.domain.StockinDetail;
import com.ruoyi.project.in.stockindetail.mapper.StockinDetailMapper;
import com.ruoyi.project.out.outStock.domain.OutStockout;
import com.ruoyi.project.out.outStock.mapper.OutStockoutMapper;
import com.ruoyi.project.out.outStockDetail.domain.OutStockoutDetail;
import com.ruoyi.project.out.outStockDetail.mapper.OutStockoutDetailMapper;
import com.ruoyi.project.port.domain.BackInOrder;
import com.ruoyi.project.port.mapper.BackInOrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 基础生产线 服务层实现
 *
 * @author sys
 * @date 2021-10-28
 */
@Service
public class StockinServiceImpl implements IStockinService {
    @Autowired
    private StockinMapper stockinMapper;

    @Autowired
    private StockinDetailMapper detailMapper;

    @Autowired
    private BasJobIdMapper basJobIdMapper;

    @Autowired
    private IStockinService stockinService;

    /**
     * 查询基础生产线信息
     *
     * @param stockinGuid 基础生产线ID
     * @return 基础生产线信息
     */
    @Override
    public Stockin selectStockinById(String stockinGuid) {
        return stockinMapper.selectStockinById(stockinGuid);
    }

    /**
     * 查询基础生产线列表
     *
     * @param stockin 基础生产线信息
     * @return 基础生产线集合
     */
    @Override
    public List<Stockin> selectStockinList(Stockin stockin) {
        if ("4".compareTo(stockin.getStatus()) > 0) {
            return stockinMapper.selectStockinList(stockin);
        } else {
            return stockinMapper.selectStockinFinishList(stockin);
        }

    }

    @Override
    public String getStockInId() {
        String type = "RD";
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String date = format.format(new Date());
        int count = basJobIdMapper.getIdByDate(type, date);
        String outStockId = "";
        if (count > 0) {
            BasJobId basJobId = basJobIdMapper.getId(type);
            if (basJobId != null) {
                String[] split = basJobId.getJobId().split(date);
                int i = Integer.parseInt(split[1]);
                if (i > 9999) {
                    i = 1;
                }
                String num = String.format("%04d", ++i);
                outStockId = type + date + num;
                basJobId.setJobId(outStockId);
                basJobIdMapper.updateBasJobId(basJobId);
            }
        } else {
            BasJobId basJobId = basJobIdMapper.getId(type);
            if (basJobId != null) {
                int i = 1;
                String num = String.format("%04d", ++i);
                outStockId = type + date + num;
                basJobId.setJobId(outStockId);
                basJobIdMapper.updateBasJobId(basJobId);
            }
        }
        return outStockId;
    }

    @Override
    public long getStockIn(String inType) {
        return stockinMapper.countStockin(inType);
    }

    @Override
    public void insertToStockin(Stockin stockin) {
        stockinMapper.insertStockin(stockin);
    }

    @Override

    public AjaxResult addSave(InStockVo inStockVo) {
        Stockin stockin = inStockVo.getStockin();
        List<StockinDetail> stockinDetailList = inStockVo.getStockinDetailList();
        String inStockId = stockinService.getStockInId();
        String guid = UUID.randomUUID().toString();
        stockin.setStockinGuid(guid);
        stockin.setStockinId(inStockId);
//		stockin.setWarehouseId("01");
        stockin.setStatus("1");// 1入库开单  2审核 3收货确认
        stockin.setStockinSource("0");
        stockin.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        //获取当前操作员
        SysUser user = (SysUser) ServletUtils.getSubject().getPrincipal();
        String userName = user.getUserName();
        stockin.setCreateManId(userName);

        // FID 自建单单据号
        stockin.setFID(inStockId);
        stockin.setWarehouseId("01");

        stockinService.insertToStockin(stockin);
        for (int i = 0; i < stockinDetailList.size(); i++) {
            stockinDetailList.get(i).setStockinDetailId(inStockId + "-" + (i + 1));
            stockinDetailList.get(i).setStockinId(inStockId);
            stockinDetailList.get(i).setStockinGuid(guid);
            stockinDetailList.get(i).setAssignNum(BigDecimal.ONE);
            stockinDetailList.get(i).setQuantityX(0);
            stockinDetailList.get(i).setQuantityJ(0);

            stockinDetailList.get(i).setSupplierId(stockinDetailList.get(i).getSupplierId());
            stockinDetailList.get(i).setCustomerId(stockinDetailList.get(i).getCustomerId());
            stockinDetailList.get(i).setProductGuid(inStockId);
            //stockinDetailList.get(i).setPrice(0);
            //批号
//			stockinDetailList.get(i).setLotNo(new SimpleDateFormat("yyyyMMdd").format(new Date()));
            stockinService.insertToStockInDetail(stockinDetailList.get(i));
        }
        return AjaxResult.success("保存成功", stockin.getStockinId());
    }

    @Override
    public void insertToStockInDetail(StockinDetail stockinDetail) {
        detailMapper.insertStockinDetail(stockinDetail);
    }

    @Override
    public String updatStatus(String ids, String status) {
        Map<String, String> map = new HashMap();
        String[] stockinIds = ids.split(",");
        for (String stockinId : stockinIds) {
            map.put("v_stockin_id", stockinId);
            map.put("v_status", status);
        }
        map.put("v_resut", null);
        map.put("v_resutmsg", null);
        stockinMapper.updateStatus(map);
        return map.get("v_resutmsg");
    }


    //	@Autowired
//	StockinDetailMapper stockinDetailMapper;
//	@Autowired
//	BackInOrderMapper backInOrderMapper;
//	@Override
//	public String handleBack(String fid) {
//		try {
//			// 根据fid查回传表 查到了就不添加了
//			BackInOrder backInOrder = new BackInOrder();
//			backInOrder.setBillId(fid);
//			backInOrder.setStatus("2");
//			List<BackInOrder> backInOrders = backInOrderMapper.selectBackInOrderListZx(backInOrder);
//
//			Stockin stockinZX = new Stockin();
//			stockinZX.setFID(fid);
//			// 根据fid搜索主单
//			List<Stockin> stockinListZX = stockinMapper.selectStockinList(stockinZX);
//			// 根据主单获取子单
//			List<StockinDetail> stockinDetailsZX = new ArrayList<>();
//			if (stockinListZX.size() != 0) {
//				String stockinId = stockinListZX.get(0).getStockinId();
//				//根据主单号 查子单
//				stockinDetailsZX = stockinDetailMapper.selectStockinDetailByStockInId(stockinId);
//			}
//			//TODO 查询子单的数量  校验  相等不回传
//			if (backInOrders.size() == stockinDetailsZX.size()) {
//				// 已成功回传 不添加
//				return "选中数据已成功回传 不作操作";
//			} else {
//				// 到此 说明要么回传失败（）status为3 要么回传表里就没数据
//				Stockin stockin = new Stockin();
//				stockin.setFID(fid);
//				// 根据fid搜索主单
//				List<Stockin> stockinList = stockinMapper.selectStockinList(stockin);
//				// 根据主单获取子单
//				if (stockinList.size() != 0) {
//					String stockinId = stockinList.get(0).getStockinId();
//					//根据主单 查子单
//					List<StockinDetail> stockinDetails = stockinDetailMapper.selectStockinDetailByStockInId(stockinId);
//					for (StockinDetail stockinDetail : stockinDetails) {
//						// 加校验 看当前子单是否已插入回传表 在回传表中只修改状态 不重复添加了
//						BackInOrder backInOrder1 = new BackInOrder();
//						backInOrder1.setBillId(fid);
//						backInOrder1.setSku(stockinDetail.getProductId());
//						backInOrder1.setLotNo(stockinDetail.getLotNo());
//						List<BackInOrder> backInOrders1 = backInOrderMapper.selectBackInOrderListZx(backInOrder1);
//						if (backInOrders1.size() != 0) {
//							continue;
//						}
//						// 获取物料码
//						String productId = stockinDetail.getProductId();
//						// 获取数量
//						BigDecimal quantity = stockinDetail.getQuantity();
//						// 获取批号
//						String lotNo = stockinDetail.getLotNo();
//						// 设置flag为1
//						String flag = "1";
//						// 组装backInOrder
//						BackInOrder backInOrder4 = new BackInOrder();
//						backInOrder4.setBillId(fid);
//						backInOrder4.setBillType(stockinList.get(0).getInType());
//						backInOrder4.setSku(productId);
//						backInOrder4.setQty(quantity);
//						backInOrder4.setLotNo(lotNo);
//						backInOrder4.setFlag(flag);
//						backInOrder4.setStatus("1");
//						// 组装好查backInOrder表 添加
//						backInOrderMapper.insertBackInOrder(backInOrder4);
//					}
//					return "重传数据已补齐 重传进行中";
//				}
//				return "入库单子单数据缺失 操作失败";
//			}
//		} catch (Exception e) {
//			return "未知错误 操作失败";
//		}
//	}
    @Autowired
    StockinDetailMapper stockinDetailMapper;
    @Autowired
    BackInOrderMapper backInOrderMapper;

    @Override
    public String handleBack(String fid) {
        try {
            // 根据fid查回传表 查到了就不添加了
            BackInOrder backInOrder = new BackInOrder();
            backInOrder.setBillId(fid);
            backInOrder.setStatus("2");
            List<BackInOrder> backInOrders = backInOrderMapper.selectBackInOrderListZx(backInOrder);
            Stockin stockinZX = new Stockin();
            stockinZX.setFID(fid);
            // 根据fid搜索主单 classNowId是1搜索入库单 是2搜索出库单
            List<Stockin> stockinListZX = stockinMapper.selectStockinList(stockinZX);
            // 根据主单获取子单
            List<StockinDetail> stockinDetailsZX = new ArrayList<>();
            if (stockinListZX.size() != 0) {
                String stockinId = stockinListZX.get(0).getStockinId();
                //根据主单号 查子单
                stockinDetailsZX = stockinDetailMapper.selectStockinDetailByStockInId(stockinId);
            }
            //TODO 查询子单的数量  校验  相等不回传
            if (backInOrders.size() == stockinDetailsZX.size()) {
                // 已成功回传 不添加
                return "选中数据已成功回传 不作操作";
            } else {
                // 到此 说明要么回传失败（）status为3 要么回传表里就没数据
                Stockin stockin = new Stockin();
                stockin.setFID(fid);
                //---------------未回传的改为待回传的----------------------
                BackInOrder backInOrderx = new BackInOrder();
                backInOrderx.setBillId(fid);
                backInOrderx.setStatus("1");
                backInOrderMapper.updateBackInOrder(backInOrderx);
                //--------------------------------------
                // 根据fid搜索主单
                List<Stockin> stockinList = stockinMapper.selectStockinList(stockin);
                // 根据主单获取子单
                if (stockinList.size() != 0) {
                    String stockinId = stockinList.get(0).getStockinId();
                    //根据主单 查子单
                    List<StockinDetail> stockinDetails = stockinDetailMapper.selectStockinDetailByStockInId(stockinId);
                    for (StockinDetail stockinDetail : stockinDetails) {
                        // 加校验 看当前子单是否已插入回传表 在回传表中只修改状态 不重复添加了
                        BackInOrder backInOrder1 = new BackInOrder();
                        backInOrder1.setBillId(fid);
                        backInOrder1.setSku(stockinDetail.getProductId());
                        backInOrder1.setLotNo(stockinDetail.getLotNo());
                        List<BackInOrder> backInOrders1 = backInOrderMapper.selectBackInOrderListZx(backInOrder1);
                        if (backInOrders1.size() != 0) {
                            continue;
                        }
                        int quantityC = stockinDetail.getQuantity().intValue();
                        if (stockinDetail.getQuantityJ() != null && quantityC == stockinDetail.getQuantityJ()) {
                            // 获取物料码
                            String productId = stockinDetail.getProductId();
                            // 获取数量
                            BigDecimal quantity = stockinDetail.getQuantity();
                            // 获取批号
                            String lotNo = stockinDetail.getLotNo();
                            // 设置flag为1
                            String flag = "1";
                            // 组装backInOrder
                            BackInOrder backInOrder4 = new BackInOrder();
                            backInOrder4.setBillId(fid);
                            backInOrder4.setBillType(stockinList.get(0).getInType());
                            backInOrder4.setSku(productId);
                            backInOrder4.setQty(quantity);
                            backInOrder4.setLotNo(lotNo);
                            backInOrder4.setFlag(flag);
                            backInOrder4.setStatus("1");
                            // 组装好查backInOrder表 添加
                            backInOrderMapper.insertBackInOrder(backInOrder4);
                        }

                    }
                    return "重传数据已补齐 重传进行中";
                }
                return "入库单子单数据缺失 操作失败";
            }
        } catch (Exception e) {
            System.err.println(e);
            return "未知错误 操作失败";
        }
    }

    @Autowired
    OutStockoutMapper outStockoutMapper;
    @Autowired
    OutStockoutDetailMapper outStockoutDetailMapper;

    @Override
    public String handleBackOut(String fid) {
        try {
            // 根据fid查回传表 查到了就不添加了
            BackInOrder backInOrder = new BackInOrder();
            backInOrder.setBillId(fid);
            backInOrder.setStatus("2");
            List<BackInOrder> backInOrders = backInOrderMapper.selectBackInOrderListZx(backInOrder);
            OutStockout outStockout = new OutStockout();
            outStockout.setFID(fid);
            // 根据fid搜索主单 classNowId是1搜索入库单 是2搜索出库单
            List<OutStockout> outStockouts = outStockoutMapper.selectOutStockoutList(outStockout);
            // 根据主单获取子单
            List<OutStockoutDetail> outStockoutDetailList = new ArrayList<>();
            if (outStockouts.size() != 0) {
                String stockoutId = outStockouts.get(0).getStockoutId();
                //根据主单号 查子单
                OutStockoutDetail outStockoutDetail = new OutStockoutDetail();
                outStockoutDetail.setStockoutId(stockoutId);
                outStockoutDetailList = outStockoutDetailMapper.selectOutStockoutDetailList(outStockoutDetail);
            }
            //TODO 查询子单的数量  校验  相等不回传
            if (backInOrders.size() == outStockoutDetailList.size()) {
                // 已成功回传 不添加
                return "选中数据已成功回传 不作操作";
            } else {
                // 到此 说明要么回传失败（）status为3 要么回传表里就没数据
                OutStockout outStockout1 = new OutStockout();
                outStockout1.setFID(fid);
                BackInOrder backInOrderx = new BackInOrder();
                backInOrderx.setBillId(fid);
                backInOrderx.setStatus("1");
                backInOrderMapper.updateBackInOrder(backInOrderx);
                // 根据fid搜索主单
                List<OutStockout> outStockouts1 = outStockoutMapper.selectOutStockoutList(outStockout1);
                // 根据主单获取子单
                if (outStockouts1.size() != 0) {
                    String stockoutId = outStockouts1.get(0).getStockoutId();
                    //根据主单 查子单
                    OutStockoutDetail outStockoutDetail = new OutStockoutDetail();
                    outStockoutDetail.setStockoutId(stockoutId);
                    List<OutStockoutDetail> outStockoutDetailList1 = outStockoutDetailMapper.selectOutStockoutDetailList(outStockoutDetail);
                    for (OutStockoutDetail outStockoutDetail1 : outStockoutDetailList1) {
                        // 加校验 看当前子单是否已插入回传表 在回传表中只修改状态 不重复添加了
                        BackInOrder backInOrder1 = new BackInOrder();
                        backInOrder1.setBillId(fid);
                        backInOrder1.setSku(outStockoutDetail1.getProductId());
                        backInOrder1.setLotNo(outStockoutDetail1.getLotNo());
                        List<BackInOrder> backInOrders1 = backInOrderMapper.selectBackInOrderListZx(backInOrder1);
                        if (backInOrders1.size() != 0) {
//                            BackInOrder backInOrderx = new BackInOrder();
//                            backInOrderx.setBillId(fid);
//                            backInOrderx.setStatus("1");
//                            backInOrderMapper.updateBackInOrder1(backInOrderx);
                            continue;
                        }
                        if (outStockoutDetail1.getAssignNum() != null && outStockoutDetail1.getAssignNum().compareTo(outStockoutDetail1.getQuantity()) == 0) {
                            // 获取物料码
                            String productId = outStockoutDetail1.getProductId();
                            // 获取数量
                            BigDecimal quantity = outStockoutDetail1.getQuantity();
                            // 获取批号
                            String lotNo = outStockoutDetail1.getLotNo();
                            // 设置flag为2
                            String flag = "2";
                            // 组装backInOrder
                            BackInOrder backInOrder4 = new BackInOrder();
                            backInOrder4.setBillId(fid);
                            backInOrder4.setBillType(outStockouts1.get(0).getOutType());
                            backInOrder4.setSku(productId);
                            backInOrder4.setQty(quantity);
                            backInOrder4.setLotNo(lotNo);
                            backInOrder4.setFlag(flag);
                            backInOrder4.setStatus("1");
                            // 组装好查backInOrder表 添加
                            backInOrderMapper.insertBackInOrder(backInOrder4);
                        }

                    }
                    return "重传数据已补齐 重传进行中";
                }
                return "入库单子单数据缺失 操作失败";
            }
        } catch (Exception e) {
            return "未知错误 操作失败";
        }
    }
}
